package jp.sourceforge.akjrcp.psp.commands;

import java.io.File;
import java.io.IOException;

import jp.sourceforge.akjrcp.psp.PSPIOCommand;
import jp.sourceforge.akjrcp.psp.PSPSyncView;
import jp.sourceforge.akjrcp.util.FileCopy;
import jp.sourceforge.akjrcp.util.FileNameUtils;

import org.apache.commons.io.FileUtils;

public class PSPMoveCommand extends AbstractIOCommand{

	public PSPMoveCommand(File src,File dest,boolean overwrite){
		setSrcFile(src);
		setDestFile(dest);
		setOverwrite(overwrite);
	}
	FileCopy fileCopy;
	public void setCanceld(boolean canceld) {
		super.setCanceld(canceld);
		if(fileCopy!=null){
			fileCopy.setCanceling(canceld);
		}
	}
	public int execCommand() {
		int ret=0;                                                                                                     
		if(!getSrcFile().exists()){
			ret= PSPIOCommand.SRC_NOT_FOUND;
		}
		
		try {
			if(!canWrite(getDestFile())){
				ret= PSPIOCommand.DEST_CANT_WRITE;
				return ret;
			}
			fileCopy=new FileCopy(getSrcFile(), getDestFile());
			int result=fileCopy.exec();
			if(result!=0){
				//faild
				if(getDestFile().exists()){
					getDestFile().delete();//remove dest;
				}
				ret= PSPIOCommand.CANCELED;
				return ret;
			}else{
				PSPSyncView.log.info("copied-movie");
			}
			
			//FileUtils.copyFile(getSrcFile(), getDestFile());
			
		} catch (IOException e) {
			
			e.printStackTrace();
			ret= PSPIOCommand.DEST_CANT_WRITE;
			return ret;
		}
		boolean result=false;
		for(int i=0;i<3;i++){//try to delete 
		PSPSyncView.log.info("delete:"+i);
		result=getSrcFile().delete();
		if(result){
			break;
		}
		System.gc();
		try {
			Thread.sleep(300);
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
		}
		if(!result){
			ret= PSPIOCommand.SRC_CANT_DELETE;
			return ret;
		}
		
		File imgFile=toPSPThumbnailFile(new File(FileNameUtils.getChangedExtensionName(getSrcFile(), "jpg",true)));
		if(imgFile!=null){
			File newFile=new File(FileNameUtils.getChangedExtensionName(getDestFile(), "jpg",true));
			try {
				FileUtils.copyFile(imgFile, newFile);
			} catch (IOException e) {
				PSPSyncView.log.warn("image move faild:+imgFile");	
				e.printStackTrace();
			}
			if(newFile.length()==imgFile.length()){//copy success
				boolean imgd=imgFile.delete();
				if(!imgd){
					PSPSyncView.log.warn("image delete faild:+imgFile");	
					}
			}
		}
		
		return ret;//ok
	}
	
	public String toString(){
		String label;
		if(isOverwrite()){
			label="Move_Overwrite:"+getSrcFile()+","+getDestFile();
		}else{
			label="Move:"+getSrcFile()+","+getDestFile();
		}
		return label;
	}

}
